package com.huiquan.vocab.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.synonymy.domain.Synonymy;
import com.huiquan.synonymy.service.SynonymyService;
import com.huiquan.vocab.dao.VocabElementWildcardDao;
import com.huiquan.vocab.dao.VocabWildcardDao;
import com.huiquan.vocab.domain.VocabElementWildcard;
import com.huiquan.vocab.domain.VocabElementWildcardDto;
import com.huiquan.vocab.domain.VocabWildcard;

@Service
public class VocabElementWildcardService extends BaseService {

	@Autowired
	private VocabElementWildcardDao vocabElementWildcardDao;
	@Autowired
	private VocabWildcardDao vocabWildcardDao;
	@Autowired
	private SynonymyService synonymyService;

	public ModelAndView list(String startStr, String vocabularyKey, String wildcardKey, String checkFlag,
			String exactSearchFlag ,String countPerPageStr) {

		Map<String, Object> param = new HashMap<>();
		if (vocabularyKey != null && !vocabularyKey.isEmpty()) {
			if (exactSearchFlag != null && exactSearchFlag.equals("1")) {
				param.put("vocabulary", vocabularyKey);
			} else {
				param.put("vocabulary", "%" + vocabularyKey + "%");
			}
		}
		if (wildcardKey != null && !wildcardKey.isEmpty()) {
			param.put("wildcard", wildcardKey);
		}
		if (checkFlag != null && !checkFlag.isEmpty()) {
			param.put("checkFlag", checkFlag);
		}
		int totalSize = vocabElementWildcardDao.retrieveSize(param);

		Map<String, Integer> pageNo ;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr, countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, startStr);
		}
		int endPage = pageNo.get("endPage");
		int start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<VocabElementWildcardDto> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = vocabElementWildcardDao.retrieveDtoList(param);
		}

		for (VocabElementWildcardDto vocabElement : list) {
			String[] sentence = getSentenceAndShowSentence(vocabElement.getSentence());
			vocabElement.setSentence(sentence[0]);
			vocabElement.setShowSentence(sentence[1]);
		}

		// 查找所有的通配符
		List<VocabWildcard> wildcardList = vocabWildcardDao.retrieveList();
		List<String> wildcardStrList = new ArrayList<>();
		for (VocabWildcard wildcard : wildcardList) {
			wildcardStrList.add(wildcard.getName() + "-" + wildcard.getProperty());
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("vocabularyKey", "词语");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, null);
		map.put("showSearch", showSearch);
		map.put("wildcardList", wildcardStrList);

		return new ModelAndView("vocab/element_index", map);
	}

	/**
	 * 根据例句获取在列表上展现的例句内容
	 * 
	 * @param value
	 * @return
	 */
	private String[] getSentenceAndShowSentence(String value) {
		// 例句的分隔符
		char sentenceSegmentFlag = 3;
		// 例句的频数分割符号
		char countSegmentFlag = 4;
		String[] sentences = value.split("\\" + sentenceSegmentFlag);
		StringBuffer sentence = new StringBuffer();
		for (int i = 0; i < sentences.length; i++) {
			// 去除例句频数
			String[] sentenceAndCount = sentences[i].split("\\" + countSegmentFlag);
			sentences[i] = sentenceAndCount[0];
			sentence.append(sentences[i]);
			if (i != (sentences.length - 1)) {
				sentence.append("\n");
			}
		}
		return new String[] { sentence.toString(), sentences[0] };
	}

	public ReturnData checkPage(String checkedIds, String unCheckedIds, User user) {

		// 将勾选的数据维护成需拆分的， 且将拆分前后的词添加如同义词
		StringBuffer errMsg = new StringBuffer();
		if (checkedIds != null && !checkedIds.isEmpty()) {
			for (String idStr : checkedIds.split(",")) {
				// 获取拆分前的词和通配符
				VocabElementWildcardDto dto = vocabElementWildcardDao.retrieveDtoById(idStr);
				String property = dto.getProperty();
				String oldName = dto.getOldName();
				String newName = dto.getNewName();

				List<String> words = new ArrayList<>();
				words.add(oldName);
				words.add(newName);

				ReturnCode rc = synonymyService.insertWordByTypeAndProperty(Synonymy.TYPE_ELEMENT, property, words,
						user, null);
				if (rc.getCode().equals(ReturnCode.SYNONYMY_WORDS_NOT_IN_SAME_DATA.getCode())) {
					if (errMsg.length() == 0) {
						errMsg.append("拆分前后的词在不同的同义词组中：");
					}
					for (String name : words) {
						errMsg.append("(");
						errMsg.append(name);
						errMsg.append(",");
						errMsg.append(property);
						errMsg.append(")，");
					}
				}
			}

			if (errMsg.length() > 0) {
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc(errMsg.toString());
				return ReturnUtil.fail(rc);
			}
			vocabElementWildcardDao.updateCheckFlagByIds(checkedIds, VocabElementWildcard.CHECK_FLAG_YES);
		}

		// 将未勾选的数据维护成不拆分的
		if (unCheckedIds != null && !unCheckedIds.isEmpty()) {
			vocabElementWildcardDao.updateCheckFlagByIds(unCheckedIds, VocabElementWildcard.CHECK_FLAG_NO);
		}

		return ReturnUtil.success();
	}

	public ReturnData getWildcardList() {
		List<VocabWildcard> list = getAllVocabWildcard();

		Map<String, Object> data = new HashMap<>();
		data.put("list", list);

		return ReturnUtil.success(data);
	}

	public List<VocabWildcard> getAllVocabWildcard() {
		return vocabWildcardDao.retrieveList();
	}

	public ReturnData addWildcard(String name, String property) {
		Long id;
		VocabWildcard vw = vocabWildcardDao.retrieveObjectByNameAndProperty(name, property);
		if (vw != null) {
			if (BaseContants.FLAG_YES.equals(vw.getDelFlag())) {
				// 如果是已删除的，则恢复
				vocabWildcardDao.restore(vw);
				id = vw.getId();
			} else {
				// 如果是未删除的则提示
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("(" + name + "-" + property + ")已存在，请确认！");

				return ReturnUtil.fail(rc);
			}
		} else {
			vw = new VocabWildcard();
			vw.setName(name);
			vw.setProperty(property);

			id = vocabWildcardDao.insert(vw);
		}

		// 添加通配符时，初始化待校验的小词通配符
		vocabElementWildcardDao.initByWildCard(vw);

		Map<String, Object> data = new HashMap<>();
		data.put("id", id);

		return ReturnUtil.success(data);
	}

	public ReturnData deleteWildcard(String id) {
		VocabWildcard vw = new VocabWildcard();
		vw.setId(Long.parseLong(id));
		vocabWildcardDao.delete(vw);

		return ReturnUtil.success();
	}

	public ReturnData initAll() {
		// 查找所有通配符，逐个初始化
		List<VocabWildcard> vwList = vocabWildcardDao.retrieveList();

		for (VocabWildcard vw : vwList) {
			vocabElementWildcardDao.initByWildCard(vw);
		}

		return ReturnUtil.success();
	}

}
